package com.ayu.shortlink.settlement.util;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 唯一ID 生成器管理器
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class GeneratorIdManager implements InitializingBean {
    private final Redisson redisson;
    private final StringRedisTemplate stringRedisTemplate;
    private static DistributedIdGenerator distributedIdGenerator;
    //最大的访问
    private final Long MAX_NODE_ID = 31L;

    /**
     * 生成唯一ID
     * @return 生成唯一ID
     */
    public String generatorID(){
        return distributedIdGenerator.generateID().toString();
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        //这块需要去Redis寻找当前的ID
        String key = "lock-settlement-generator-id";
        RLock lock = redisson.getLock(key);

        lock.lock();
        try {
            String DISTRIBUTE_NODE_ID_KEY = "settlement-distribute-node-id-key";
            log.info("正在生成机器ID");
            Long NODE_ID = Optional.ofNullable(stringRedisTemplate.opsForValue().increment(DISTRIBUTE_NODE_ID_KEY))
                    .orElse(0L);
            //判断机器ID是否合理
            if (NODE_ID > MAX_NODE_ID){
                NODE_ID = 0L;
                stringRedisTemplate.opsForValue().set(DISTRIBUTE_NODE_ID_KEY, "0");
            }
            //实例化唯一ID生成器
            distributedIdGenerator = new DistributedIdGenerator(NODE_ID);
        }finally {
            lock.unlock();
        }
    }
}
